<?php
session_start();
class GenerateMonthlyBillsController{
	function GenerateMonthlyBillsController(){
		$query = "SELECT * from unit where isoccupied = 1";
		$result = mysql_query($query)
		or die(mysql_error());  
		while($row = mysql_fetch_array($result)){
			//echo $row['unit_name'];
			$this->generateBills($row['unit_name']);
		}
	
		//echo "===========Generate Monthly Bills===========";
		
	}
	
	function generateBills($unit_name){
		$query1 = "SELECT sum(amount) totalpayment FROM `payment` WHERE month(date_received) = month(curdate()) -1 and year(date_received) = year(curdate()) and unit='$unit_name'";
		$result1 = mysql_query($query1)
		or die(mysql_error());  
		$row1 = mysql_fetch_array( $result1 );
		if(!isset($row1['totalpayment'])){
			$totalpayment = 0;
		}
		else
			$totalpayment = $row1['totalpayment'];
		
		$query2 = "SELECT monthly_rent from unit where unit_name = '$unit_name'";
		$result2 = mysql_query($query2)
		or die(mysql_error());  
		$row2 = mysql_fetch_array( $result2 );
		$monthlyrent = $row2['monthly_rent'];
		$totalunpaid = 0;
		$totalunpaid = $monthlyrent - $totalpayment;
		$total = $totalpayment + $totalunpaid;
		$query = "INSERT into bill(prev_bill,month,year,amount_payed,unit_name,amount_this_month,total) values ($totalunpaid,month(curdate()),year(curdate()),$totalpayment,'$unit_name',$monthlyrent,$total )";
		//echo $query;
		mysql_query($query);
		//echo $query;
		//echo "=============".$totalunpaid."=======";
	}
}
?>